package dp.mobile.entity;

import java.io.Serializable;

import javax.microedition.khronos.opengles.GL10;

import android.graphics.Point;
import dp.mobile.glwrapper.GLTexture;
import dp.mobile.glwrapper.GameRenderer;
import dp.mobile.system.Utilities;

public class Bullet implements Serializable {
	private static final long serialVersionUID = 5689020495673660265L;
	private static final String TAG = "Bullet";
	
	protected Bullet() {
		//Initialize
		mX		= 0;
		mY		= 0;
		mTimer	= 0;
		mData	= null;
		mTarget	= null;
		mActive	= true;
	}

	public Bullet(BulletData data, Enemy target, int x, int y, int bonusDamage) {
		//Default
		this();

		//Save data
		mX			= x;
		mY			= y;
		mData		= data;
		mTexture	= data.getImage();
		mTarget		= target;

		mBulletAngle = 0;
		
		mBonusDamage = bonusDamage;
	}
	
	public Enemy getTarget()	{	return mTarget;	}
	public boolean isActive()	{	return mActive;	}
	public BulletData getData() {	return mData;		}
	public int getDamage(){
		return mData.getDamage() + mBonusDamage;
	}

	public void damage(Enemy enemy) {
		//Does buff exist?
		Buff Effect = null;
		if (mData.getBuffData() != null) Effect = new Buff(mData.getBuffData());

		//Damage enemy
		enemy.damage(getDamage(), Effect);
	}
	
	public void update(long time) {
		//Skip if no enemy
		if (mTarget == null || mTarget.getHealth() <= 0) mActive = false;

		//If active
		if (mActive) {
			//Get difference
			float offsetFactor = (float)time / (float)(mData.getDuration() - mTimer);
			
			//Calculate bullet direction
			Point center = mTarget.getCenter();
			final float dY = center.y - mY;
			final float dX = center.x - mX;

			mBulletAngle = (90 - (float)Math.toDegrees(Math.atan2(dY, dX))) % 360;

			//Increase timer
			mTimer += time;
			if (mTimer >= mData.getDuration()) mActive = false;
			else {
				//Move
				mX = (int)(mX - offsetFactor * -dX);
				mY = (int)(mY - offsetFactor * -dY);
			}
		}
	}
	
	public void draw(GL10 gl) {
		if (mTexture == null) return;
		
		//Draw
		GameRenderer.instance().draw(gl, mTexture, mX, mY, mTexture.Width, mTexture.Height, Utilities.BULLET_DEPTH, mBulletAngle);
	}
	
	protected int			mX;
	protected int			mY;
	protected long			mTimer;
	protected BulletData	mData;
	protected boolean		mActive;
	protected Enemy			mTarget;
	protected GLTexture		mTexture;

	protected float			mBulletAngle;
	protected int			mBonusDamage;
}
